package com.ljkj.cordial.chat.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.FileSizeUtil;
import com.nic.view.util.JToast;
import com.yanzhenjie.album.AlbumFile;

import java.io.File;

/**
 * 文件选取
 */
public class AnnexUtil {
    public final static int REQUEST_CODE_ATTACH_FILE = 765;

    /**
     * 启动文件选择界面：
     *
     * @param activity
     */
    public static void searchAnnex(Activity activity, int requestCode) {

        Intent intent = new Intent("intent.action.SELECT_FOLDER_OR_FILE");
        intent.putExtra("request_type_int", 6); // REQUEST_CODE_ATTACH_PATH = 6
        activity.startActivityForResult(intent, requestCode);
    }

    ////    获取返回值：
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        switch (requestCode) {
//            case REQUEST_CODE_ATTACH_FILE:
//                getFilerResult(data);
//                break;
//        }
//    }
    public static void setRequestCodeAttachFile(Activity activity, Intent data, OnInsertFileListener listener) {
        String path = AndroidFileUtil.getPath2uri(activity, getFilerResult(data));
//        JLog.d("->"+path);
        if (!TextUtils.isEmpty(path)) {
            if (FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB) > 100.0f) {
                JToast.show(activity, "文件大小不能超过100M", Toast.LENGTH_SHORT);
                return;
            }
            AlbumFile albumFile = AlbumManageUtil.getInstance().getAlbumFile(activity, path);
            Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_EXTRA_FILE);
            if (listener != null) {
                listener.onCallback(path, fileId);
            }

        }
    }

    private static Uri getFilerResult(Intent data) {
        Uri uri = null;
//        String currentDir = null;
//        String fileName = null;
        if (data.hasExtra("result_dir_or_file")) {
            String path = data.getStringExtra("result_dir_or_file");
            File file = new File(path);
            uri = Uri.fromFile(file);
//            currentDir = file.getParent();
//            fileName = file.getName();
        } else {
            uri = data.getData();
//            currentDir = data.getStringExtra("currentDir");
//            fileName = data.getStringExtra("fileName");
        }
        return uri;
    }

    public interface OnInsertFileListener {
        void onCallback(String filePath, Long fileId);
    }
}
